package com.zjitc.chapter09.dao.impl;

import com.zjitc.chapter09.dao.AccountDao;
import com.zjitc.chapter09.domain.Account;
import lombok.Setter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Setter
public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;
    @Override
    public int addAccount(Account account) {
        String sql = "insert into account(name,balance) values(?,?)";
        int result = jdbcTemplate.update(sql, account.getName(), account.getBalance());
        return result;
    }

    @Override
    public int updateAccount(Account account) {
        String sql = "update account set name=?,balance=? where id=?";
        Object[] params = {account.getName(), account.getBalance(), account.getId()};
        int result = jdbcTemplate.update(sql, params);
        return result;
    }

    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id=?";
        int result = jdbcTemplate.update(sql, id);
        return result;
    }

    @Override
    public Account findAccountById(int id) {
        String sql = "select * from account where id=?";
        RowMapper<Account> rowMapper=new BeanPropertyRowMapper<>(Account.class);
        return jdbcTemplate.queryForObject(sql, rowMapper, id);
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select * from account";
        RowMapper<Account> rowMapper=new BeanPropertyRowMapper<>(Account.class);
        return jdbcTemplate.query(sql, rowMapper);
    }

    @Override
    public void transfer(String sourceName, String targetName, BigDecimal money) {
        String sql = "update account set balance=balance-? where name=?";
        jdbcTemplate.update(sql, money, sourceName);
        int i = 1 / 0;
        sql = "update account set balance=balance+? where name=?";
        jdbcTemplate.update(sql, money, targetName);
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
    public void transfer2(String sourceName, String targetName, BigDecimal money) {
        String sql = "update account set balance=balance-? where name=?";
        jdbcTemplate.update(sql, money, sourceName);
        int i = 1 / 0;
        sql = "update account set balance=balance+? where name=?";
        jdbcTemplate.update(sql, money, targetName);
    }
}
